package scatter.banner.rest.service;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import scatter.banner.pojo.po.Banner;
import scatter.common.rest.service.IBaseService;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * <p>
 * 横幅表 服务类
 * </p>
 *
 * @author yw
 * @since 2021-01-26
 */
public interface IBannerService extends IBaseService<Banner> {

	/**
	 * 可用横幅列表
	 * @param groupFlags 分组标识，支持以逗号分隔的多个
	 * @return
	 */
	default List<Banner> listAvailable(String groupFlags){
		List<String> groupFlagList = Optional.ofNullable(groupFlags).map(item ->item.split(",")).map(item -> newArrayList(item)).orElse(null);
		List<Banner> result = list(Wrappers.<Banner>lambdaQuery()
				.eq(Banner::getIsDisabled,false)
				.in(!isEmpty(groupFlagList),Banner::getGroupFlag,groupFlagList)
				// 后面加 id ，稳定排序
				.orderByAsc(Banner::getSeq).orderByAsc(Banner::getId)
		);
		// 过滤时间，时间为空的算永久
		if (!isEmpty(result)) {
			result = result.stream().filter(item -> {
				LocalDateTime start  = Optional.ofNullable(item.getStartAt()).orElse(LocalDateTimeUtil.of(DateUtil.yesterday()));
				LocalDateTime end  = Optional.ofNullable(item.getEndAt()).orElse(LocalDateTimeUtil.of(DateUtil.tomorrow()));
				return LocalDateTime.now().isAfter(start) && LocalDateTime.now().isBefore(end);
			}).collect(Collectors.toList());
		}
		return result;
	}

}
